<template>
    <div>
        <ul>
            <li v-for="(item, index) in treeData" :key="item.id">
                {{ item.label }}
                <span @click="moveUp(index)" :disabled="index === 0">⬆️</span>
                <span @click="moveDown(index)" :disabled="index === treeData.length - 1">⬇️</span>

                <!-- 递归子节点 -->
                <tree-node v-if="item.children && item.children.length" :nodes="item.children"
                    @node-moved="handleChildMove(item.id, $event)" />
            </li>
        </ul>
    </div>
</template>

<script>
import { ref } from 'vue';

export default {
    name: 'TreeNode',
    props: {
        nodes: {
            type: Array,
            required: true
        }
    },
    setup(props, { emit }) {
        const treeData = ref(props.nodes);

        // 上移节点
        const moveUp = (index) => {
            if (index <= 0) return;

            const temp = treeData.value[index - 1];
            treeData.value[index - 1] = treeData.value[index];
            treeData.value[index] = temp;

            emit('node-moved', treeData.value);
        };

        // 下移节点
        const moveDown = (index) => {
            if (index >= treeData.value.length - 1) return;

            const temp = treeData.value[index + 1];
            treeData.value[index + 1] = treeData.value[index];
            treeData.value[index] = temp;

            emit('node-moved', treeData.value);
        };

        // 处理子节点移动
        const handleChildMove = (parentId, newChildren) => {
            const parentNode = findNode(treeData.value, parentId);
            if (parentNode) {
                parentNode.children = newChildren;
                emit('node-moved', treeData.value);
            }
        };

        // 辅助函数：查找节点
        const findNode = (nodes, id) => {
            for (const node of nodes) {
                if (node.id === id) return node;
                if (node.children) {
                    const found = findNode(node.children, id);
                    if (found) return found;
                }
            }
            return null;
        };

        return {
            treeData,
            moveUp,
            moveDown,
            handleChildMove
        };
    }
};
</script>
<style scoped lang="less">
div {
    padding: 10px;

    ul {
        list-style: none;
        padding: 0;
        margin: 0;

        li {
            margin: 0;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            position: relative;

            &:hover {
                background-color: #f5f5f5;
            }

            &.active {
                background-color: #f5f5f5;
            }
        }

        li span {
            display: inline-block;
            cursor: pointer;
            padding: 0;
            margin: 0;
            font-size: 16px;
        }
    }
}
</style>